package org.linlinjava.litemall.admin.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.annotations.VisibleForTesting;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.admin.errorcode.ErrorCodeConstants;
import org.linlinjava.litemall.admin.vo.packagegoods.AdminLumierePackageCategoryGoodsRespVO;
import org.linlinjava.litemall.admin.vo.packagegoods.AdminLumierePackageCategoryRespVO;
import org.linlinjava.litemall.admin.vo.packagegoods.AdminLumierePackageSpecificationsVO;
import org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallCategoryService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LumierePackageCategoryGoodsService;
import org.linlinjava.litemall.db.service.LumierePackageCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @auth :ply
 * @date 2024/6/18 17:32
 * @Description TODO
 * 管理套餐类目管理服务
 */
@Transactional
@Service
@RequiredArgsConstructor
public class AdminLumierePackageCategoryService {

    private final LumierePackageCategoryService lumierePackageCategoryService;

    private final LumierePackageCategoryGoodsService lumierePackageCategoryGoodsService;

    private final LitemallGoodsService litemallGoodsService;

    private final LitemallCategoryService litemallCategoryService;

    /**
     * 根据查询条件查询套餐类目列表
     * @param packageId 查询条件
     * @return 套餐类目列表
     */
    public ResponseUtil.Response listLumierePackageCategory(Integer packageId) {

        // 构建查询条件
        LambdaQueryWrapper<LumierePackageCategory> queryWrapper = new LambdaQueryWrapper<>();

        Optional.ofNullable(packageId)
                .filter(pid -> pid != 0) // 判断packageId是否不等于0
                .ifPresent(pid -> queryWrapper.eq(LumierePackageCategory::getPackageId, pid));

        // 返回结果
        return ResponseUtil.ok(lumierePackageCategoryService.list(queryWrapper));
    }


    public ResponseUtil.Response listLumierePackageCategoryGoods(Integer packageId, Integer packageCategoryId) {
        //获取类目下的 套餐商品
        List<LumierePackageCategoryGoods> packageCategoryGoodsList = lumierePackageCategoryGoodsService.list(Wrappers.lambdaQuery(LumierePackageCategoryGoods.class)
                .eq(LumierePackageCategoryGoods::getPackageId, packageId)
                .eq(LumierePackageCategoryGoods::getPackageCategoryId,packageCategoryId));

        List<AdminLumierePackageCategoryGoodsRespVO> packageCategoryGoodsRespVOS = packageCategoryGoodsList.stream().map(packageCategoryGoods -> {
            AdminLumierePackageCategoryGoodsRespVO packageCategoryRespVO = new AdminLumierePackageCategoryGoodsRespVO();
            packageCategoryRespVO.setId(packageCategoryGoods.getId());
            packageCategoryRespVO.setPackageId(packageCategoryGoods.getPackageId());
            packageCategoryRespVO.setCategoryId(packageCategoryGoods.getCategoryId());
            packageCategoryRespVO.setPackageCategoryId(packageCategoryGoods.getPackageCategoryId());
            packageCategoryRespVO.setGoodsId(packageCategoryGoods.getGoodsId());
            packageCategoryRespVO.setQuantity(packageCategoryGoods.getQuantity());
            //packageCategoryRespVO.setAmount(packageCategoryGoods.getAmount());
            //packageCategoryRespVO.setUnit(packageCategoryGoods.getUnit());
            packageCategoryRespVO.setIsDefault(packageCategoryGoods.getIsDefault());
            //packageCategoryRespVO.setSpecifications(JSONUtil.toList(JSONUtil.parseArray(packageCategoryGoods.getSpecifications()), AdminLumierePackageSpecificationsVO.class));

            //商品信息
            LitemallGoods litemallGoods = litemallGoodsService.findById(packageCategoryGoods.getGoodsId());
            packageCategoryRespVO.setGoods(litemallGoods);
            LitemallCategory litemallCategory = litemallCategoryService.findById(packageCategoryGoods.getCategoryId());
            packageCategoryRespVO.setCategoryName(litemallCategory.getName());
            return packageCategoryRespVO;
        }).collect(Collectors.toList());
        return ResponseUtil.ok(packageCategoryGoodsRespVOS);
    }

    /**
     * 添加新的类目。
     * @param lumierePackageCategory 待添加的类目对象
     * @return 添加操作的响应结果
     */
    public ResponseUtil.Response addLumierePackageCategory(LumierePackageCategory lumierePackageCategory,Integer adminUserId) {
        Optional<String> categoryNameOptional = Optional.ofNullable(lumierePackageCategory.getCategoryName());
        if(!categoryNameOptional.isPresent()){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.LUMIERE_PACKAGE_CATEGORY_NAME_EMPTY);
        }
        //校验重复
        if(lumierePackageCategory.getId()==null){
            validatePackageCategoryExist(lumierePackageCategory.getCategoryName(),lumierePackageCategory.getPackageId());
        }
        //创建人
        lumierePackageCategory.setAddUserId(adminUserId.toString());
        return lumierePackageCategoryService.saveOrUpdate(lumierePackageCategory) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    @VisibleForTesting
    private void validatePackageCategoryExist(String categoryName,Integer packageId){
        // 构建查询条件
        long count = lumierePackageCategoryService.count(Wrappers.lambdaQuery(LumierePackageCategory.class)
                .eq(LumierePackageCategory::getCategoryName, categoryName)
                .eq(LumierePackageCategory::getPackageId, packageId));

        if(count>0){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.LUMIERE_PACKAGE_CATEGORY_EXIST);
        }
    }

    /**
     * 更新类目信息。
     * @param lumierePackageCategory 待更新的类目对象
     * @return 更新操作的响应结果
     */
    public ResponseUtil.Response updateLumierePackageCategory(LumierePackageCategory lumierePackageCategory) {
        return lumierePackageCategoryService.updateById(lumierePackageCategory) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    /**
     * 根据指定ID删除类目。
     * @param id 待删除的类目ID
     * @return 删除操作的响应结果
     */
    public ResponseUtil.Response deleteLumierePackageCategory(Integer id){
        //删除类目下面所有商品
        List<LumierePackageCategoryGoods> packageCategoryGoodsList = lumierePackageCategoryGoodsService.list(Wrappers.lambdaQuery(LumierePackageCategoryGoods.class)
                .eq(LumierePackageCategoryGoods::getPackageCategoryId, id));
        lumierePackageCategoryGoodsService.removeBatchByIds(packageCategoryGoodsList);
        return lumierePackageCategoryService.removeById(id) ? ResponseUtil.ok() : ResponseUtil.fail();
    }



}
